package com.business.user.utils;

import com.business.common.dto.R;
import com.business.common.enums.BusinessExceptionEnum;
import com.business.common.exception.BusinessException;
import com.business.common.utils.FormatValidUtil;
import com.business.common.utils.StrKit;
import com.business.redis.RedisLock;
import com.business.redis.constant.RedisKeyConstant;
import com.business.redis.utils.RedisKeysUtil;
import com.business.redis.utils.RedisUtil;
import com.business.user.entity.UserDto;

public class UserUtil {

    /**
     * 校验验证码
     *
     * @param phone
     * @param  verificationCode
     * @return
     */
    public static Integer validateCode(String phone, String verificationCode) {
        if (StrKit.isBlank(phone)) {
            throw new BusinessException(BusinessExceptionEnum.PHONE_NULL);
        }
        if(!FormatValidUtil.matchPhone(phone)){
            throw new BusinessException(BusinessExceptionEnum.PHONE_PATTERN_ERROR);
        }
        if (verificationCode == null) {
            throw new BusinessException(BusinessExceptionEnum.VERIFICATION_NUll);
        }
        //TODO 万能验证码
        if(verificationCode.equals("8888")){
            return 1;
        }

        String key = String.format(RedisKeyConstant.USER_GET_VERIFICATION_CODE_FLAG, phone);
        RedisLock redisLock = RedisLock.build(key);
        try{
            redisLock.lock();//获取锁
            if (RedisUtil.hasKey(key) == false) {
                throw new BusinessException(BusinessExceptionEnum.VERIFICATION_CODE_OVERTIME);
            }
            String sessionCode = RedisUtil.getValue(key) + "";
            if (!verificationCode.equals(sessionCode)) {
                throw new BusinessException(BusinessExceptionEnum.VERIFICATION_CODE_ERROR);
            }
            //删除key
            RedisUtil.delValue(key);
        }finally {
            redisLock.unlock();
        }

        return 1;
    }

}
